class CopyrightGenerator {
    constructor() {
        this.currentSerialNumber = null;
        this.currentData = {};
        this.initEventListeners();
    }

    showProgress(text = '正在处理中...') {
        const container = document.getElementById('progressContainer');
        const textElement = document.getElementById('progressText');
        textElement.textContent = text;
        container.style.display = 'block';
        container.scrollIntoView({ behavior: 'smooth', block: 'center' });
    }

    hideProgress() {
        document.getElementById('progressContainer').style.display = 'none';
    }

    updateProgress(text) {
        document.getElementById('progressText').textContent = text;
    }

    initEventListeners() {
        // 生成摘要按钮
        document.getElementById('generateSummaryBtn').addEventListener('click', () => {
            this.generateSummary();
        });

        // 一键生成完整版按钮
        document.getElementById('generateFullBtn').addEventListener('click', () => {
            this.generateFull();
        });

        // 序列号查询
        document.getElementById('querySerialBtn').addEventListener('click', () => {
            this.queryBySerial();
        });

        // 保存所有内容
        document.getElementById('saveAllBtn').addEventListener('click', () => {
            this.saveAllContent();
        });

        // 监听回车键查询序列号
        document.getElementById('serialNumber').addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.queryBySerial();
            }
        });

        // 添加textarea自适应高度功能
        this.initAutoResizeTextareas();
    }

    initAutoResizeTextareas() {
        const textareas = document.querySelectorAll('.editable-content');
        
        textareas.forEach(textarea => {
            // 初始调整高度
            this.adjustTextareaHeight(textarea);
            
            // 监听输入事件
            textarea.addEventListener('input', () => {
                this.adjustTextareaHeight(textarea);
            });
            
            // 监听窗口大小变化
            window.addEventListener('resize', () => {
                this.adjustTextareaHeight(textarea);
            });
        });
    }

    adjustTextareaHeight(textarea) {
        // 重置高度以获取正确的scrollHeight
        textarea.style.height = 'auto';
        
        // 计算新高度，限制在最小和最大高度之间
        const newHeight = Math.max(
            120, // 最小高度
            Math.min(textarea.scrollHeight + 2, 400) // 最大高度
        );
        
        textarea.style.height = newHeight + 'px';
    }

    async generateSummary() {
        const description = document.getElementById('description').value.trim();
        const language = document.getElementById('language').value;
        const version = document.getElementById('version').value.trim();

        if (!description || !language || !version) {
            this.showError('请填写所有必填字段');
            return;
        }

        this.setLoading('generateFullBtn', true);
        this.hideError();
        this.showProgress('正在智能分析软件信息...');

        try {
            const response = await fetch('/api/generate-summary', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    description,
                    language,
                    version
                })
            });

            const result = await response.json();

            if (result.success) {
                this.displaySummaryResults(result.data);
                this.showSuccess('摘要生成成功！');
            } else {
                this.showError(result.error || '生成失败');
            }
        } catch (error) {
            this.showError('网络错误：' + error.message);
        } finally {
            this.setLoading('generateSummaryBtn', false);
            this.hideProgress();
        }
    }

    async generateFull() {
        const summaries = this.getEditableSummaries();

        if (!summaries.form || !summaries.code || !summaries.document) {
            this.showError('请确保所有摘要都已填写');
            return;
        }

        this.setLoading('generateSummaryBtn', true);
        this.hideError();

        try {
            const response = await fetch('/api/generate-full', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    application_form_summary: summaries.form,
                    code_summary: summaries.code,
                    document_summary: summaries.document
                })
            });

            const result = await response.json();

            if (result.success) {
                this.displayFullResults(result.data);
                this.showSuccess('完整版本生成成功！');
                
                // 保存内容并获取序列号
                await this.saveAllContent();
            } else {
                this.showError(result.error || '生成失败');
            }
        } catch (error) {
            this.showError('网络错误：' + error.message);
        } finally {
            this.setLoading('generateFullBtn', false);
            this.hideProgress();
        }
    }

    async generateFullForType(type) {
        const summaries = this.getEditableSummaries();
        
        if (!summaries.form || !summaries.code || !summaries.document) {
            this.showError('请确保所有摘要都已填写');
            return;
        }

        const typeKey = this.getTypeKey(type);
        const summaryContent = summaries[type];
        
        if (!summaryContent.trim()) {
            this.showError(`请先填写${this.getTypeName(type)}摘要`);
            return;
        }

        const btn = document.querySelector(`[data-type="${type}"]`);
        this.setLoading(null, true, btn);
        this.showProgress(`正在生成${this.getTypeName(type)}完整版...`);

        try {
            const response = await fetch('/api/generate-full-for-type', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    summary: summaryContent,
                    type: type
                })
            });

            const result = await response.json();

            if (result.success) {
                this.displaySingleFullResult(type, result.data);
                this.showSuccess(`${this.getTypeName(type)}完整版生成成功！`);
            } else {
                this.showError(result.error || '生成失败');
            }
        } catch (error) {
            this.showError('网络错误：' + error.message);
        } finally {
            this.setLoading(null, false, btn);
            this.hideProgress();
        }
    }

    displaySummaryResults(data) {
        document.getElementById('formSummary').value = data.application_form_summary;
        document.getElementById('codeSummary').value = data.code_summary;
        document.getElementById('documentSummary').value = data.document_summary;

        // 显示使用成本
        

        // 显示结果区域
        document.getElementById('summaryResults').style.display = 'block';
        
        // 隐藏完整版结果区域
        document.getElementById('fullResults').style.display = 'none';
        
        // 保存当前数据
        this.currentData = {
            description: document.getElementById('description').value,
            language: document.getElementById('language').value,
            version: document.getElementById('version').value,
            application_form_summary: data.application_form_summary,
            code_summary: data.code_summary,
            document_summary: data.document_summary
        };
        
        // 更新按钮状态
        document.getElementById('generateSummaryBtn').textContent = '一键生成完整版';
        document.getElementById('generateSummaryBtn').onclick = () => this.generateFull();
    }

    getTypeKey(type) {
        const typeMap = {
            'form': 'application_form',
            'code': 'code',
            'document': 'document'
        };
        return typeMap[type] || type;
    }

    displaySingleFullResult(type, data) {
        const typeKey = this.getTypeKey(type);
        const elementId = `${typeKey}Full`;
        const element = document.getElementById(elementId);
        
        if (element) {
            element.textContent = data[`${typeKey}_full`];
            element.parentElement.style.display = 'block';
        }
    }

    displayFullResults(data) {
        document.getElementById('formFull').textContent = data.application_form_full;
        document.getElementById('codeFull').textContent = data.code_full;
        document.getElementById('documentFull').textContent = data.document_full;

        // 显示使用成本
        

        // 显示结果区域
        document.getElementById('fullResults').style.display = 'block';
    }

    async generateFull() {
        const summaries = this.getEditableSummaries();

        if (!summaries.form || !summaries.code || !summaries.document) {
            this.showError('请确保所有摘要都已填写');
            return;
        }

        this.setLoading('generateFullBtn', true);
        this.showProgress('正在生成完整版本申请材料...');

        try {
            const response = await fetch('/api/generate-full', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    application_form_summary: summaries.form,
                    code_summary: summaries.code,
                    document_summary: summaries.document,
                    type: 'all'
                })
            });

            const result = await response.json();

            if (result.success) {
                this.displayFullResults(result.data);
                this.showSuccess('完整版本生成成功！');
                
                // 保存序列号
                if (result.serial_number) {
                    this.currentSerialNumber = result.serial_number;
                    this.displaySerialNumber(result.serial_number);
                }
            } else {
                this.showError(result.error || '生成失败');
            }
        } catch (error) {
            this.showError('网络错误：' + error.message);
        } finally {
            this.setLoading('generateFullBtn', true, false);
            this.hideProgress();
        }
    }

    async queryBySerial() {
        const serialNumber = document.getElementById('serialNumber').value.trim();
        
        if (!serialNumber) {
            this.showError('请输入序列号');
            return;
        }

        this.setLoading('querySerialBtn', true);
        this.showProgress('正在查询序列号信息...');

        try {
            const response = await fetch('/api/query-serial', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    serial_number: serialNumber
                })
            });

            const result = await response.json();

            if (result.success) {
                this.displayQueryResults(result.data);
                this.showSuccess('查询成功！');
            } else {
                this.showError(result.error || '未找到相关内容');
            }
        } catch (error) {
            this.showError('网络错误：' + error.message);
        } finally {
            this.setLoading('querySerialBtn', true, false);
            this.hideProgress();
        }
    }

    async saveAllContent() {
        const data = {
            description: document.getElementById('description').value,
            language: document.getElementById('language').value,
            version: document.getElementById('version').value,
            application_form_summary: document.getElementById('formSummary').value,
            code_summary: document.getElementById('codeSummary').value,
            document_summary: document.getElementById('documentSummary').value,
            application_form_full: document.getElementById('formFull').textContent,
            code_full: document.getElementById('codeFull').textContent,
            document_full: document.getElementById('documentFull').textContent
        };

        this.setLoading('saveAllBtn', true);
        this.showProgress('正在保存所有内容...');

        try {
            const response = await fetch('/api/save-content', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            });

            const result = await response.json();

            if (result.success) {
                this.currentSerialNumber = result.serial_number;
                this.displaySerialNumber(result.serial_number);
                this.showSuccess('内容已保存！序列号：' + result.serial_number);
            } else {
                this.showError(result.error || '保存失败');
            }
        } catch (error) {
            this.showError('网络错误：' + error.message);
        } finally {
            this.setLoading('saveAllBtn', true, false);
            this.hideProgress();
        }
    }

    displayQueryResults(data) {
        // 填充表单
        document.getElementById('description').value = data.description;
        document.getElementById('language').value = data.language;
        document.getElementById('version').value = data.version;

        // 填充摘要
        document.getElementById('formSummary').value = data.application_form_summary;
        document.getElementById('codeSummary').value = data.code_summary;
        document.getElementById('documentSummary').value = data.document_summary;

        // 填充完整版
        document.getElementById('formFull').textContent = data.application_form_full;
        document.getElementById('codeFull').textContent = data.code_full;
        document.getElementById('documentFull').textContent = data.document_full;

        // 显示结果区域
        document.getElementById('summaryResults').style.display = 'block';
        document.getElementById('fullResults').style.display = 'block';
        
        // 显示序列号
        this.currentSerialNumber = data.serial_number;
        this.displaySerialNumber(data.serial_number);

        // 更新按钮
        document.getElementById('generateSummaryBtn').textContent = '一键生成完整版';
        document.getElementById('generateSummaryBtn').onclick = () => this.generateFull();
    }

    displaySerialNumber(serialNumber) {
        document.getElementById('currentSerialNumber').textContent = serialNumber;
        document.getElementById('serialNumberDisplay').style.display = 'block';
    }

    getEditableSummaries() {
        return {
            form: document.getElementById('formSummary').value,
            code: document.getElementById('codeSummary').value,
            document: document.getElementById('documentSummary').value
        };
    }

    getTypeName(type) {
        const typeMap = {
            'form': '登记申请表',
            'code': '源程序',
            'document': '说明文档'
        };
        return typeMap[type] || type;
    }

    async copyToClipboard(targetId) {
        const element = document.getElementById(targetId);
        let textToCopy;
        
        if (element.tagName === 'TEXTAREA') {
            textToCopy = element.value;
        } else {
            textToCopy = element.textContent;
        }
        
        try {
            await navigator.clipboard.writeText(textToCopy);
            this.showCopySuccess();
        } catch (err) {
            // 降级方案
            const textArea = document.createElement('textarea');
            textArea.value = textToCopy;
            document.body.appendChild(textArea);
            textArea.select();
            document.execCommand('copy');
            document.body.removeChild(textArea);
            this.showCopySuccess();
        }
    }

    showCopySuccess() {
        const successDiv = document.createElement('div');
        successDiv.className = 'copy-success';
        successDiv.textContent = '✅ 已复制到剪贴板';
        document.body.appendChild(successDiv);
        
        setTimeout(() => {
            successDiv.remove();
        }, 2000);
    }

    setLoading(elementId, isLoading, element = null) {
        const target = element || document.getElementById(elementId);
        if (!target) return;
        
        if (isLoading) {
            target.disabled = true;
            target.innerHTML = '<span class="loading-dots">处理中</span>';
            target.style.opacity = '0.7';
        } else {
            target.disabled = false;
            target.style.opacity = '1';
            const originalText = target.dataset.originalText || 
                (target.id === 'generateSummaryBtn' ? '智能生成摘要' : 
                 target.id === 'generateFullBtn' ? '一键生成完整版' :
                 target.id === 'querySerialBtn' ? '立即查询' :
                 target.id === 'saveAllBtn' ? '💾 保存所有内容' : '生成完整版本');
            target.innerHTML = originalText;
        }
    }

    showError(message) {
        const errorDiv = document.getElementById('errorMessage');
        errorDiv.textContent = message;
        errorDiv.style.display = 'block';
        errorDiv.scrollIntoView({ behavior: 'smooth', block: 'center' });
        
        setTimeout(() => {
            this.hideError();
        }, 5000);
    }

    hideError() {
        document.getElementById('errorMessage').style.display = 'none';
    }

    showSuccess(message) {
        const successDiv = document.getElementById('successMessage');
        successDiv.textContent = message;
        successDiv.style.display = 'block';
        successDiv.scrollIntoView({ behavior: 'smooth', block: 'center' });
        
        setTimeout(() => {
            successDiv.style.display = 'none';
        }, 3000);
    }
}

// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
    new CopyrightGenerator();
});